﻿namespace Lite.Messaging.Msmq
{
    using System;
    using System.Globalization;
    using System.Messaging;

    public class MsmqMessageQueueFactory
        : IMessageQueueFactory
    {
        private static string GetPathFromName(string queueName)
        {
            return Environment.MachineName + @"\private$\" + queueName;
        }

        #region IMessageQueueFactory Members

        public IMessageQueue GetMessageQueue(string queueName)
        {
            if (queueName == null)
            {
                throw new ArgumentNullException("queueName");
            }

            string queuePath = GetPathFromName(queueName);

            if (!MessageQueue.Exists(queuePath))
            {
                throw new QueueNotFoundException(string.Format(CultureInfo.InvariantCulture, "Could not find MSMQ '{0}'.", queuePath));
            }

            return new MsmqMessageQueue(new MessageQueue(queuePath));
        }

        public bool Exists(string queueName)
        {
            return MessageQueue.Exists(GetPathFromName(queueName));
        }

        public IMessageQueue CreateMessageQueue(string queueName)
        {
            return new MsmqMessageQueue(MessageQueue.Create(GetPathFromName(queueName)));
        }

        public IQueueMonitor CreateQueueMonitor(string queueName)
        {
            if (queueName == null)
            {
                throw new ArgumentNullException("queueName");
            }

            string queuePath = GetPathFromName(queueName);

            if (!MessageQueue.Exists(queuePath))
            {
                throw new QueueNotFoundException(string.Format(CultureInfo.InvariantCulture, "Could not find MSMQ '{0}'.", queuePath));
            }

            MsmqMessageQueue messageQueue = new MsmqMessageQueue(new MessageQueue(queuePath));

            return new MsmqQueueMonitor(messageQueue);
        }

        #endregion
    }
}
